package util

import (
	"time"

	"github.com/mediocregopher/radix.v2/pool"
	"github.com/mediocregopher/radix.v2/redis"
)

var group *SafeMap

type Redis struct {
	pool *pool.Pool
}

func init() {
	group = NewSafeMap()
}

func NewRedis(addr string) Redis {
	var r Redis
	if val, ok := group.Get(addr); ok {
		r = val.(Redis)
	} else {
		r = new(addr, 2, 3*time.Second)
	}
	return r
}

func new(addr string, size int, timeout time.Duration) Redis {
	var p *pool.Pool
	p, _ = pool.NewCustom("tcp", addr, size, func(network, addr string) (*redis.Client, error) {
		c, err := redis.DialTimeout(network, addr, timeout)
		return c, err
	})
	return Redis{pool: p}
}

func (r Redis) Cmd(cmd string, args ...interface{}) *redis.Resp {
	return r.pool.Cmd(cmd, args)
}
